package com.example.service;

import cn.hutool.core.util.StrUtil;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.exception.CustomerException;
import javax.annotation.Resource;

import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.mapper.AdminMapper;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

@Service
public class AdminService {


    @Autowired
    AdminMapper adminMapper;


    public String admin(String name) {
        if ("admin".equals(name)) {
            return "请求成功";
        } else {
            throw new CustomerException("账号错误");
        }
    }


    public void add(Admin admin) {
// 根据新的账号查询数据库 是否存在同样的账号的数据
      Admin dbAdmin  =  adminMapper.selectByUsername(admin.getUsername());
        if (dbAdmin != null) {
            throw new CustomerException("账号重复");
        }
        //默认密码
      if(StrUtil.isBlank(admin.getPassword())){
            admin.setPassword("admin");
        }
        admin.setRole("ADMIN");
        adminMapper.insert(admin);
    }
    //修改
    public void update(Admin admin) {
            adminMapper.updateById(admin);
    }
    //删除
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    //查询
    public List<Admin> selectAll(Admin admin) {
        return adminMapper.selectAll(admin);
    }
    //批量删除
    public void deleteBatch(List<Admin> list) {
        for (Admin admin : list) {
            this.deleteById(admin.getId());

        }
    }

   //JWT
    public Admin selectById(String id){
        return adminMapper.selectById(id);
    }

    public PageInfo<Admin> selectPage(Integer pageNum, Integer pageSize, Admin admin) {
   //开启分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }


    public Admin login(Account account) {
        // 验证账号是否存在
        Admin dbAdmin = adminMapper.selectByUsername(account.getUsername());
        if (dbAdmin == null) {
            throw new CustomerException("账号不存在");
        }
        // 验证密码是否正确
        if (!dbAdmin.getPassword().equals(account.getPassword())) {
            throw new CustomerException("账号或密码错误");
        }
        //创建token并返回给前端
        String token = TokenUtils.createToken(dbAdmin.getId() + "-" + "ADMIN",dbAdmin.getPassword());
        dbAdmin.setToken(token);
        return dbAdmin;

    }

}
